Skip to main content

Chapter 10 - depends_on

What if one resource needs another to exist before it's created?

Meta Arguments


  • depends on - to handle hidden module dependencies
  • count - to create multiple instances based on a count.
  • foreach - to create multiple instances according to a map or set of strings
  • provider - to select a non default provider config
  • lifecycle - resource behavior can be altered using this block
  • provisioners and connections (not a true metadata) - - extra action after resource creation -ie, install something on the resource

Depends on


Available in all module blocks and in all resource blocks, regardless of resource type.

  • must be a list of references to other resources or child modules
  • arbitrary expressions are not allowed
  • This is a last resort. If you are using a lot of depends_on, you're probably doing something you shouldn't be.

Small depends_on demo


  1. Plan and apply this code:
# Create Virtual Network
resource "azurerm_virtual_network" "myvnet" {
name = "myvnet-1"
address_space = ["10.0.0.0/16"]
location = azurerm_resource_group.myrg.location
resource_group_name = azurerm_resource_group.myrg.name
}

# Create Subnet
resource "azurerm_subnet" "mysubnet" {
name = "mysubnet-1"
resource_group_name = azurerm_resource_group.myrg.name
virtual_network_name = azurerm_virtual_network.myvnet.name
address_prefixes = ["10.0.2.0/24"]
}

# Create Public IP Address
resource "azurerm_public_ip" "mypublicip" {
name = "mypublicip-1"
resource_group_name = azurerm_resource_group.myrg.name
location = azurerm_resource_group.myrg.location
allocation_method = "Static"
domain_name_label = "app1-vm-${random_string.myrandom.id}"
tags = {
environment = "Dev"
}

}

# Create Network Interface
resource "azurerm_network_interface" "myvmnic" {
name = "vmnic"
location = azurerm_resource_group.myrg.location
resource_group_name = azurerm_resource_group.myrg.name

ip_configuration {
name = "internal"
subnet_id = azurerm_subnet.mysubnet.id
private_ip_address_allocation = "Dynamic"
public_ip_address_id = azurerm_public_ip.mypublicip.id
}
}

  1. Notice that the public IP isn't created last
    image.png
  2. add the depends on block for the public IP resource
  3. Destroy the previous infra, and run a new plan and apply.
  4. Notice that the public IP is created after the vnet and subnet
    image.png